package zjitc.web.servlet;

import zjitc.domain.Test;
import zjitc.service.UserService;
import zjitc.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 设置编码
        request.setCharacterEncoding("utf-8");

        //2. 获取数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");


        //3. 封装User对象
        Test user = new Test();
        user.setUsername(username);
        user.setPassword(password);


        //4. 调用Service查询
        //5. 判断是否登录成功
        UserService service = new UserServiceImpl();
        user = service.login(username,password);
        if(user!=null){
            //登录成功
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //跳转页面
            response.sendRedirect(request.getContextPath()+"/userListServlet");
        }else{
            //登录失败
            request.setAttribute("login_msg","用户名或密码错误");
            //跳转登录页面
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }




    }
}
